﻿using System.Collections.Generic;

namespace Miao
{
    /// <summary>
    /// 表示一个等差数列(整数)
    /// </summary>
    public readonly struct ArithmeticProgressionInt : IArithmeticProgression<int, RangeInt>
    {
        public int first { get; }
        public int commonDifference { get; }

        public int this[int index] => first + commonDifference * index;

        public static ArithmeticProgressionInt Create(int min, int max, int internvalCount)
        {
            return new ArithmeticProgressionInt(min, (max - min) / internvalCount);
        }

        public ArithmeticProgressionInt(int first, int commonDifference)
        {
            this.first = first;
            this.commonDifference = commonDifference;
        }

        public RangeInt GetInterval(int index)
        {
            int min = this[index];
            return new RangeInt(min, min + commonDifference);
        }
        public int GetClosestTerm(int value)
        {
            int intervalIndex = GetIntervalIndex(value);
            int result = intervalIndex * commonDifference;
            float remainder = value % commonDifference;
            return remainder < commonDifference * 0.5f ? result : result + commonDifference;
        }
        public int GetTermIndex(int value)
        {
            int intervalIndex = GetIntervalIndex(value);
            float remainder = value % commonDifference;
            return remainder < commonDifference * 0.5f ? intervalIndex : (intervalIndex + 1);
        }
        public int GetIntervalIndex(int value)
        {
            return value / commonDifference;
        }

        public int[] ToArray(int length)
        {
            int[] result = new int[length];
            for (int i = 0; i < length; i++) result[i] = this[i];
            return result;
        }
        public void ToArray(int[] result, int length)
        {
            for (int i = 0; i < length; i++) result[i] = this[i];
        }
        public void ToList(IList<int> result, int length)
        {
            for (int i = 0; i < length; i++) result.Add(this[i]);
        }
    }
}